﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Cheetah_Fast_Banking_App.Cryptography
{
    public class Hasher : IHasher
    {
        HashAlgorithm _hasher;
        public Type HashAlgorithmType
        {
            get
            {
                if (_hasher == null)
                    return null;

                return _hasher.GetType();
            }
        }

        Mixer _mixer;
        public Mixer Mixer
        {
            get { return _mixer; }
            set
            {
                if (value == null)
                    _mixer = Mixer.Default;
                else
                    _mixer = value;
            }
        }

        Encoding _encoding;
        public Encoding Encoding
        {
            get { return _encoding; }
            set
            {
                if (value == null)
                    _encoding = Encoding.Default;
                else
                    _encoding = value;
            }
        }

        /// <summary>
        /// Creates an instance of Hasher using the specified HashAlgorithm
        /// </summary>
        public Hasher(HashAlgorithm hashAlgorithm)
            : this(hashAlgorithm, Encoding.Default)
        { }

        public Hasher(HashAlgorithm hashAlgorithm, Encoding encoding)
            : this(hashAlgorithm, encoding, new Mixer())
        { }

        public Hasher(HashAlgorithm hashAlgorithm, Encoding encoding, Mixer mixer)
        {
            // check for null?
            this._hasher = hashAlgorithm;
            this._encoding = encoding;
            this._mixer = mixer;
        }

        public string GetHash(string plainText)
        {
            byte[] plainTextBytes = this.Encoding.GetBytes(plainText);
            byte[] hashBytes = _hasher.ComputeHash(plainTextBytes);
            string hash = ConvertToString(hashBytes);
            return hash;
        }

        protected virtual string ConvertToString(byte[] hashBytes)
        {
            return Convert.ToBase64String(hashBytes);
        }

        public string GetHash(string plainText, string salt)
        {
            return GetHash(_mixer.Mix(plainText, salt));
        }
    }
}
